﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using WorkFlowCore.Plugins;
using WorkFlowCore.UserSelectors;

namespace WorkFlowCore.Framework.UserSelectors
{
    [UserSelector("自定义选择（http）")]
    [PluginDescription("参数：selections=[url,选项数组] 如果传url，要求get请求，返回格式参考 【选项数组】")]
    [PluginDescription("选项数组：[{\"Id\":\"\",Name:\"\"}]")]
    [PluginDescription("参数：users=[url,用户字典] 如果传url，接收 post 请求，传参 {SelectionId:string selections 中的Id,Expression:string 表达式,WorkTask:object 当前流程实例,CurrentStep:object 当前审批步骤 }，返回格式参考 【用户数组】")]
    [PluginDescription("用户数组：[{\"Id\":\"\",Name:\"\"}]")]
    [PluginDescription("用户字典：{\"SelectionId\":[{Id:\"\",Name:\"\"}]} SelectionId 值为 selections 中的Id")]
    [PluginDescription("建议组合方式 selections:url + users:url； selections:选项数组 + users:url 或 用户字典")]
    public class UserSelectorDefaultHttp : IUserSelector, IConfigurable
    {
        ConfigureContext configureContext;
        public Task Configure(ConfigureContext configureContext)
        {
            this.configureContext = configureContext;
            return Task.CompletedTask;
        }

        public List<Selection> GetSelections()
        {
            try
            {
                var selectionsParemeter = configureContext.Parameters.GetOrDefault("selections") ?? "";
                if (selectionsParemeter.StartsWith("http"))
                {
                    var httpClient = new HttpClient();
                    var data = httpClient.GetStringAsync(selectionsParemeter).Result;
                    return JsonConvert.DeserializeObject<List<Selection>>(data);
                }
                else
                {
                    return JsonConvert.DeserializeObject<List<Selection>>(selectionsParemeter);
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                Console.Error.WriteLine(ex.StackTrace);
                return new List<Selection>();
            }
        }

        public List<User> GetUsers(SelectorInput input)
        {
            try
            {
                var usersParemeter = configureContext.Parameters.GetOrDefault("users") ?? "";
                if (usersParemeter.StartsWith("http"))
                {
                    var httpClient = new HttpClient();
                    var resp = httpClient.PostAsync(usersParemeter, new StringContent(JsonConvert.SerializeObject(input),Encoding.UTF8, "application/json")).Result;
                    var data = resp.Content.ReadAsStringAsync().Result;
                    return JsonConvert.DeserializeObject<List<User>>(data);
                }
                else
                {
                    var jObject = JObject.Parse(usersParemeter);
                    return JsonConvert.DeserializeObject<List<User>>(jObject[input.SelectionId].ToString());
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                Console.Error.WriteLine(ex.StackTrace);
                return new List<User>();
            }
        }
    }
}
